<template>
    <div class="flex-1" @click="popupShow = true">
        <el-input
            :model-value="getLink"
            :disabled="disabled"
            placeholder="请选择链接"
            readonly
        >
            <template #suffix>
                <icon v-if="!modelValue?.path" name="el-icon-ArrowRight" />
                <icon
                    v-else
                    name="el-icon-Close"
                    @click.stop="!disabled && emits('update:modelValue', {})"
                />
            </template>
        </el-input>

        <popup
            :show="popupShow"
            width="700px"
            title="链接选择"
            @close="popupShow = false"
            @confirm="handleConfirm"
        >
            <link-content v-if="popupShow" v-model="activeLink" :client="client" />
        </popup>
    </div>
</template>

<script setup lang="ts">
import { LinkTypeEnum, type Link } from '.'
import LinkContent from './index.vue'

const props = defineProps({
    // Link对象
    modelValue: {
        type: Object as PropType<Link>,
        required: true
    },
    // 是否禁止选择
    disabled: {
        type: Boolean,
        default: false
    },
    // 终端选择类型: [pc, h5]
    client: {
        type: String,
        default: 'pc'
    }
})

const emits = defineEmits<{
    (event: 'update:modelValue', value: any): void
}>()

// 弹窗状态
const popupShow = ref<boolean>(false)

// 激活链接
const activeLink = ref<Link>({
    type: LinkTypeEnum.BASIC,
    path: ''
})

// 获取链接
const getLink = computed(() => {
    switch (props.modelValue?.type) {
        case LinkTypeEnum.BASIC:
            return props.modelValue.name
        case LinkTypeEnum.CUSTOM:
            return props.modelValue.path
        default:
            return props.modelValue?.name
    }
})

/**
 * 确认选择
 */
const handleConfirm = () => {
    emits('update:modelValue', { ...activeLink.value })
}

/**
 * 监听变化
 */
watch(
    () => props.modelValue,
    (value) => {
        if (value?.type) {
            activeLink.value = value as Link
        }
    },
    {
        immediate: true
    }
)
</script>
